<template>
	<div class="prod-detail relative">
		<van-list
			v-model="loadRecommend.load"
			:finished="loadRecommend.finished"
			:offset="detail ? 1 : 100"
			:immediate-check="false"
			@load="recommend"
		>
			<van-nav-bar class="prod-navbar">
				<van-icon 
					v-if="!$is_from_app && !isVisitorPrice"
					slot="left" 
					class-prefix="ucai-icon" 
					name="fanhuijian" 
					@click="goback" 
				/>
				<template slot="right">
					<van-icon 
						v-if="!$is_from_app && is_mobile"
						class-prefix="ucai-icon" 
						name="fenxiang1" 
						@click="shareTips = true"
					/>
					<!-- <van-icon class-prefix="ucai-icon" name="gouwuchewode" /> -->
					<van-icon 
						v-if="!$is_from_app" 
						class-prefix="ucai-icon" 
						name="wodezhongxin" 
						@click="role ? $goPage('profile') : $goPage('login', { role: '0' })" 
					/>
				</template>
			</van-nav-bar>

			<van-swipe 
				class="prod-swipe"
				:autoplay="3000"
			>
				<van-swipe-item 
					tag="a" 
					v-for="(swipe, index) in banner" 
					:key="index"
				>
					<img :src="swipe" v-lazy="swipe">
				</van-swipe-item>
			</van-swipe>

			<van-row class="swipe-bottom-text" type="flex" justify="space-between" v-if="detail">
				<van-col span="12" class="van-ellipsis">{{detail.zone_name}}</van-col>
				<van-col span="12" class="text-right" v-if="detail.interested">{{detail.interested || ''}}人感兴趣</van-col>
			</van-row>

			<div class="prod-info">
				<van-skeleton
					title
					:row="3"
					v-if="detail"
					:loading="loading"
				>
					<div class="bg-white mg-btm-ls title-wrap">
						<p>{{detail.name}}</p>
						<van-tag 
							plain 
							class="c-gray mg-rgt-sm" 
							v-for="(tag, index) in detail.themes" 
							:key="index"
						>{{tag.name}}</van-tag>
					</div>
					<!-- 地址 -->
					<van-row 
						class="bg-white mg-btm-ls"
						type="flex" 
						justify="space-between" 
						v-if="address"
						@click="map"
					>
						<van-col span="20">
							<van-icon class-prefix="ucai-icon" name="zuobiao" class="c-gray-l" />
							<span class="van-ellipsis prod-addr">{{address}}</span>
						</van-col>
						<van-col span="4" class="c-gray-l text-right">
							地图
							<van-icon class-prefix="ucai-icon" name="arrow_rgt" />
						</van-col>
					</van-row>
				</van-skeleton>
				<!-- 套餐 -->
				<van-skeleton
					title
					:row="3"
					v-if="packages"
					:loading="loading"
				>
					<h2 class="bg-white van-hairline--bottom">商品套餐</h2>
					<div class="bg-white mg-btm-ls">
						<van-row 
							class="category-list"
							type="flex"
							justify="space-between"
							v-for="(cate, index) in packages"
							:key="index"
						>
							<van-col span="16" @click="showNotic(index)">
								<h4>{{cate.name}}</h4>
								<p class="c-gray mg-top-xs" v-if="!isVisitorPrice">建议零售价：￥{{parseFloat(cate.sale_price)}} 
									<van-tag v-if="cate.earn" plain class="c-buy">赚￥{{parseFloat(cate.earn)}}</van-tag>
								</p>
								<p class="c-gray-l mg-top-sm">
									已售{{cate.sales}} | 
									<span class="c-main">预订须知
										<van-icon class-prefix="ucai-icon" name="arrow_rgt" />
									</span>
								</p>
							</van-col>
							<van-col span="8" class="text-right" @click="gotopage('booking', index)">
								<p class="c-buy font-xs">￥<strong>{{parseFloat(cate.trade_price)}}</strong>起</p>
								<del class=" block c-gray-l mg-top-xs">￥{{parseFloat(cate.origin_price)}}</del>
								<van-button 
									class="mg-top-xs" 
									:type="isVisitorPrice ? 'buy-customer' : 'buy'" 
									size="small" 
									:text="(cate.remain_stock > 0 || cate.has_unlimited_stock == '1') ? (isVisitorPrice ? '立即预订' : '立即采购') : '已售罄'" 
									:disabled="disabledBtn || (cate.remain_stock <= 0 && cate.has_unlimited_stock == '0')"
								/>
							</van-col>
						</van-row>
					</div>
				</van-skeleton>

				<!-- 产品信息 -->
				<van-skeleton
					title
					:row="3"
					v-if="content"
					:loading="loading"
				>
					<h2 class="bg-white van-hairline--bottom">产品信息</h2>
					<div class="bg-white mg-btm-ls">
						<div class="show-wrap" ref="detailContent" :class="!contentConfig.allContent && 'show-less'">
							<div v-html="content"></div>
							<div class="pd-top-xl" v-if="use_explain && use_explain.length">
								<h3>其他说明</h3>
								<div v-for="(rule, index) in use_explain" :key="index">
									<p class="pd-top">【{{rule.name || ''}}】</p>
									<p v-html="rule.content"></p>
								</div>
							</div>
						</div>
						<p 
							v-if="contentConfig.showTogBtn"
							class="show-more" 
							@click="contentConfig.allContent = !contentConfig.allContent"
						>{{contentConfig.allContent ? '收起' : '展开'}}
							<van-icon class-prefix="ucai-icon" name="arrow_rgt" :class="contentConfig.allContent && 'up'" />
						</p>
					</div>
				</van-skeleton>
				<!-- 预订须知 -->
				<van-skeleton
					title
					:row="3"
					v-if="instruction"
					:loading="loading"
				>
					<h2 class="bg-white van-hairline--bottom">预订须知</h2>
					<div class="bg-white mg-btm-ls" ref="noticContent">
						<div v-if="instruction.kind">
							<div  v-for="(rule, index) in instruction" :key="index">
								<p class="pd-top-xl">【{{rule.name}}】</p>
								<p v-html="rule.content"></p>
							</div>
						</div>
						<div 
							v-else 
							class="show-wrap" 
							:class="!noticConfig.allContent && 'show-less'"
							v-html="instruction.instruction"
						></div>
						<p 
							v-if="noticConfig.showTogBtn"
							class="show-more" 
							@click="noticConfig.allContent = !noticConfig.allContent"
						>{{noticConfig.allContent ? '收起' : '展开'}}
							<van-icon class-prefix="ucai-icon" name="arrow_rgt" :class="noticConfig.allContent && 'up'" />
						</p>
					</div>
				</van-skeleton>

				<h2 v-show="recommendList" class="bg-white van-hairline--bottom">景区其他产品</h2>
				<div v-show="recommendList" class="bg-white mg-btm-no pd-btm-no pd-hor-no">
					<prod-item :list="recommendList" v-if="recommendList" />
				</div>
			</div>
		</van-list>

		<van-goods-action>
			<van-goods-action-icon text="客服" @click="kefu">
				<van-icon 
					slot="icon" 
					class-prefix="ucai-icon" 
					:name="'kefuzhongxin' + (showKefu ? '_on' : '')" 
					:class="showKefu && 'c-main'"
				/>
			</van-goods-action-icon>
			<van-goods-action-icon v-if="!isVisitorPrice" :text="collected ? '已收藏' : '收藏'" @click="collectedProd">
				<van-icon 
					slot="icon" 
					class-prefix="ucai-icon" 
					:class="collected && 'c-main'"
					:name="collected ? 'yishoucang' : 'shoucang'" 
				/>
			</van-goods-action-icon>
			<van-goods-action-button 
				class="c-white add-price-bg"
				type="info" 
				text="加价转发" 
				@click="addPrice" 
				v-if="!isVisitorPrice"
			/>
			<van-goods-action-button 
			 	:disabled="disabledBtn || no_stock"
				:type="isVisitorPrice ? 'buy-customer' : 'buy'"
				:text="no_stock ? '已售罄' : (isHidden ? '产品已下架' : isVisitorPrice ? '立即预订' : '立即采购')" 
				@click="gotopage('booking', 0)" 
			/>
		</van-goods-action>

		<!-- 套餐的须知弹出 -->
		<cate-notic 
			v-if="packages"
			ref="cateNotic" 
			:prod-id="id" 
			:cate="cate" 
		/>
		<!-- 加价转发 -->
		<add-price
			ref="add_prices"
			:detail="detail"
			:packages="packages"
			:banner="banner"
		/>

		<kefu-popup 
			ref="kefuInfo" 
			:tel="service.phone || ''" 
			:name="service.name || ''" 
			:service_name="service.name || ''"
			:service_company="service.shop_name || ''"
			:role_type="isVisitorPrice ? 'customer' : 'distributor'"
			@cancle="kefu"
		/>

		<!-- 弹窗-分享 -->
    <share-overlay :show="shareTips" ref="share-overlay" />

		<slogan class="mg-footer" />
	</div>
</template>
<script>
import { 
		Skeleton,
		List,
    Icon,
    Button,
    Swipe,
    SwipeItem,
    Row,
    Col,
    NavBar,
		Tag,
		Overlay,
		GoodsAction,
		GoodsActionIcon,
		GoodsActionButton,
    Toast
 } from "vant";
import {
	getDetail,
	getRecommend,
	addCollectProd,
	delCollectProd
} from '@/api/modules/product'
import ProdItem from '../components/item'
import CateNotic from '../components/cate-notic'
import AddPrice from '../components/add-price'
import Kefu from '@cmpt/popup/kefu'
import ShareOverlay from "@cmpt/share"
import Slogan from '@cmpt/slogan'

import { getRole, getRolePrice } from '@utils/role'
import { BROWSER } from '@utils/utils'

export default {
	name: 'detail',
	components: {
		[Skeleton.name]: Skeleton,
		[List.name]: List,
		[Icon.name]: Icon,
		[Button.name]: Button,
		[Swipe.name]: Swipe,
		[SwipeItem.name]: SwipeItem,
		[Row.name]: Row,
		[Col.name]: Col,
		[NavBar.name]: NavBar,
		[Tag.name]: Tag,
		[Overlay.name]: Overlay,
		[GoodsAction.name]: GoodsAction,
		[GoodsActionIcon.name]: GoodsActionIcon,
		[GoodsActionButton.name]: GoodsActionButton,
		[ProdItem.name]: ProdItem,
		[CateNotic.name]: CateNotic,
		[AddPrice.name]: AddPrice,
		[Kefu.name]: Kefu,
		[Slogan.name]: Slogan,
		[ShareOverlay.name]: ShareOverlay,
	},
	data(){
		return {
			role: getRole(),
			loading: true,
			cate: {},
			contentConfig: {
				allContent: true,
				showTogBtn: false
			},
			noticConfig: {
				allContent: true,
				showTogBtn: false
			},
			collected: false, // 是否收藏
			is_release: true, // 是否可买
			isHidden: false, // 是否隐藏
			no_stock: false, // 是否全部已售罄
			detail: null,
			address: null,
			point: null, // 地图
			banner: null, // 轮播
			packages: null, // 套餐
			content: null, // 详情
			use_explain: null, // 其他说明
			instruction: null, // 预定须知
			showKefu: false,
			service: { // 客服
				name: null,
				phone: null,
				shop_name: null
			},
			shareTips: false, // 分享遮罩
			disabledBtn: this.$getUrlParam('preview') || false,
			id: Number(this.$getUrlParam('id')),
			isVisitorPrice: getRolePrice() === '0', // 是否展示游客价
			secret: this.$getUrlParam('secret'), // 加密字符串
			recommendList: null, // 推荐
			loadRecommend: {
				load: false,
				finished: false
			},
			is_mobile: BROWSER.mobile, 
		}
	},
	watch: {
		content(nw) {
			this.$nextTick(() => {
				this.content && this.toggleContent()
			})
		}
	},
	created() {
		this.load()
	},
	methods: {
		async load() {
			let data = {id: this.id}
			if(this.isVisitorPrice) data.secret = this.secret
			getDetail(data)
				.then(res => {
					this.$set_page_title(res.data.name)
					if(res.data.is_release == 0){
						const back_name = this.isVisitorPrice ? 'profile' : '' // 分销商：还回上一页，如果没有上一页，返回采购中心。游客：返回用户中心
						if(!this.disabledBtn){
							alert('产品已下架');
							this.$goPageBack(back_name)
						}else{
							this.isHidden = true
						}
					}
					
					if(res.data.packages){

						res.data.packages.forEach(item => {
							item.earn = (Number(item.sale_price) - Number(item.trade_price)).toFixed(2)
							item.remain_stock = Number(item.remain_stock)
						})
						this.packages = res.data.packages
						this.no_stock = this.packages.filter(v => (v.has_unlimited_stock == 0 && v.remain_stock <= 0)).length > 0
					}else{
						this.disabledBtn = true
					}

						this.detail = res.data
						this.loading = false
						this.collected = this.detail.is_favorite == 1
						this.is_release = this.detail.is_release == 1

						this.banner = this.detail.detail.picture.product_pic
						
						this.content = this.detail.detail.content

						this.use_explain = JSON.parse(this.detail.detail.use_explain)
						
						this.instruction = {
								instruction: this.detail.detail.instruction,
								kind: this.detail.detail.instruction_kind
							}

						this.service = {
							name: this.detail.detail.extra.service_name,
							phone: this.detail.detail.extra.service_phone,
							shop_name: this.detail.detail.extra.company_name
						}
						this.themes = this.detail.themes
						this.address = this.detail.address
						this.point = {
							lat: this.detail.detail.extra.lat,
							lng: this.detail.detail.extra.lng,
						}

						// 设置微信、app分享
						this.$nextTick(() => {
							this.$set_share({
								title: this.detail.name,
								desc: this.$refs.detailContent ? this.$refs.detailContent.textContent.slice(0, 50) : '', // 产品详情前50字
								imgUrl: this.detail.share_thumb || (this.banner||[])[0] // 产品主图
							})
						})
				})
				.catch(err => {
					const msg = err.data.msg || '其他原因'
					alert(msg)
					this.$goPageBack()
				})
		},
		// 展开详情
		toggleContent() {
			const refContent = this.$refs.detailContent
			const refNotic = this.$refs.noticContent
			if(refContent && refContent.offsetHeight > 270){
				this.contentConfig.showTogBtn = true
				this.contentConfig.allContent = false
			}

			if(refNotic && refNotic.offsetHeight > 270){
				this.noticConfig.showTogBtn = true
				this.noticConfig.allContent = true
			}
		},
		map() {
			const lat = this.point.lat,
						lng = this.point.lng,
						name = this.address
			if(this.$is_from_wx){
				require.ensure(['@utils/wechat'], (require) => {
          const wechat = require('@utils/wechat')
          wechat.map({
						latitude: lat,
						longitude: lng,
						name: name,
						address: name,
					})
        }, 'wechat')
			}else{
				window.location.href = `https://apis.map.qq.com/uri/v1/search?keyword=${name}&center=${lat},${lng}&radius=1000&referer=myapp`
			}
			
		},
		// 查看套餐的须知
		showNotic(index) {
			this.cate = this.detail.packages[index]
			this.$refs.cateNotic.init()
		},
		// 推荐产品
		recommend () {
			// 仅在分销商登录时展示推荐
			if(this.role !== '1'){
				this.loadRecommend = {
					load: false,
					finished: true
				}
				return
			}
			getRecommend(this.id)
			.then(res => {
				this.recommendList = res.data.list
				this.show_related_prod = this.recommendList && this.recommendList.length > 0
				this.loadRecommend = {
					load: false,
					finished: true
				}
			})
		},
		// 返回
		goback () {
			this.$goPageBack()
		},
		// 跳转页面，立即预定/立即采购
		gotopage (url, index) {
			let params = {}
			if(index >= 0) {
				params = {
					product_id: this.id,
				}
				if(this.packages){
					const cate = this.packages[index]
					params.package_id = cate.id
				}
				if(this.isVisitorPrice) {
					params.secret = this.secret
				}
			}
			this.$goPage(url, params)
		},
		// 客服
		kefu () {
			this.showKefu = !this.showKefu
			this.$refs.kefuInfo.init(this.showKefu)
		},
		// 收藏
		collectedProd () {
			const ids = [this.id]
			if(this.collected){
				delCollectProd(ids).then(res => {
					this.collected = false
					Toast('已取消收藏')
				})
			}else{
				addCollectProd(ids).then(res => {
					this.collected = true
					Toast('收藏成功')
				})
			}
		},
		// 弹出加价转发
		addPrice() {
			this.$refs.add_prices.init()
		}
	}
}
</script>

<style lang="less" scoped>
@import "~@style_m/mod/prod-detail";
</style>